#!/usr/bin/ruby
require "rubygems"
require "opengl"
require "glut"
require "m3g"
require "pp"


class MyGLUTWidget
  def initialize
    GLUT.Init
    GLUT.InitWindowSize 256, 256
    GLUT.InitDisplayMode GLUT::GLUT_DOUBLE | GLUT::GLUT_RGB | GLUT::GLUT_DEPTH
    GLUT.CreateWindow "Ruby-M3G"

    initialize_scene

    GLUT.ReshapeFunc  method(:reshape).to_proc()
    GLUT.DisplayFunc  method(:display).to_proc()
    GLUT.KeyboardFunc method(:keyboard).to_proc()
    GLUT.MouseFunc    method(:mouse).to_proc()
    GLUT.IdleFunc     method(:idle).to_proc()

  end

  def initialize_scene

    controller = M3G::AnimationController.new
    keyframe_fovy = M3G::KeyframeSequence.new 3, 1, M3G::KeyframeSequence::LINEAR

    frame_fovy = [[45], [90], [45]]
    keyframe_fovy.keyframe[0] = 0, frame_fovy[0]
    keyframe_fovy.keyframe[1] = 100, frame_fovy[1]
    keyframe_fovy.keyframe[2] = 200, frame_fovy[2]
    keyframe_fovy.repeat_mode = M3G::KeyframeSequence::LOOP
    keyframe_fovy.valid_range = 0, 2
    keyframe_fovy.duration    = 200
    
    animation_fovy = M3G::AnimationTrack.new keyframe_fovy, M3G::AnimationTrack::FIELD_OF_VIEW
    animation_fovy.controller = controller

    position_values = [10,-10,0, 10,10,0, -10,-10,0, -10,10,0]
    positions = M3G::VertexArray.new 4, 3, 2
    positions.values[0,4] = position_values    

    scale = 1
    bias  = [0,0,0]
    vertices = M3G::VertexBuffer.new
    vertices.positions = positions, scale, bias

    strips = [4]
    tris = M3G::TriangleStripArray.new 0, strips

    mat = M3G::Material.new
    mat.color[M3G::Material::DIFFUSE] = 0x7f4c4cb2  # 0.3 0.3 0.7

    app = M3G::Appearance.new
    app.material = mat

    mesh = M3G::Mesh.new vertices, tris, app

    cam = M3G::Camera.new
    cam.look_at 0,0,50,
    0,0,0,
    0.1,1,0
    cam.animation_track << animation_fovy

    @wld = M3G::World.new
    @wld.active_camera = cam  
    @wld.child << cam
    @wld.child << mesh

    @world_time = 0
  end

  def reshape width, height
    g3d = M3G::Graphics3D::instance
    g3d.viewport = 0,0,width,height
    @wld.active_camera.perspective = 45, width/(height*1.0), 0.1, 100
  end

  def display
    g3d = M3G::Graphics3D::instance
    g3d.render @wld
    GLUT.SwapBuffers()
  end
  
  def keyboard key, x, y
    if key == 113  # 'q'
      exit
    elsif key == 32 # ' '
      puts "main: time = #{@world_time}"
      @wld.animate @world_time
      @world_time += 2
    end
    GLUT.PostRedisplay
  end

  def mouse button, state, x, y
  end

  def idle
    GLUT.PostRedisplay
  end

  def start
    GLUT.MainLoop
  end

end


MyGLUTWidget.new.start

